import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)


import { refreshPage, error, success, setUserInfoToSession, getUserInfoFromSession, clearSessionStorage } from "@/utils/utils";
import { login } from "@/api";
import { logout } from '../api';

export default new Vuex.Store({
  state: {
    isLogin: true,
    user: getUserInfoFromSession() || {},
  },
  mutations: {
    changeLogin(state, payload) { // 改变登录状态
      state.isLogin = payload;
    },
    userData(state, data) { // 登录成功更改state.user的值
      state.user = data;
      // 用户信息存入session
      setUserInfoToSession(data);
    },
    changeAvatar(state, data) {
      state.user = { ...state.user, avatar: data.avatar }
      // 更新session
      setUserInfoToSession(state.user);
    },
  },
  actions: {
    asyncChangeLogin({ commit }, payload) {
      commit('changeLogin', payload)
    },
    // 登录
    async login({ commit }, payload) {
      const { data, instance } = payload;
      let result = await login({ data })
      if (result.code === 1) {
        success(instance, result.msg);
        // 将表单项置空
        instance.formInline.username = '';
        instance.formInline.password = '';

        // 改变isLogin为true
        commit('changeLogin', true);
        commit('userData', result);
        // 隐藏弹窗
        instance.$emit('changeVisible', false);

        // 如果是从写文章回来的话，跳转到写文章
        const from = instance.$route.query.from
        if (from === '/write') {
          instance.$router.push({ path: from })
        }
      } else {
        error(instance, result.msg);
      }
    },
    async logout({ commit }, instance) {
      let noAlert = instance.noAlert
      if (instance.noAlert) {
        instance = instance.instance;
      }
      const res = await logout()
      if (res.code == 1) {
        !noAlert && success(instance, res.msg);
        // 改变isLogin 为false
        commit('changeLogin', false)
        commit('userData', {})

        // 清除sessionStorage
        clearSessionStorage('userInfo');
      } else {
        error(instance, res.msg);
      }
    },
    // 刷新登录
    async refresh({ commit }) {
      const r = await refreshPage();
      if (r.code == 1) {
        commit('changeLogin', true);
      } else {
        commit('changeLogin', false);
        // 刷新的时候如果没有登录状态，那么清空sessionStorage的信息
        clearSessionStorage('userInfo');
      }
      return r;
    },
  },
  modules: {
  }
})
